/*
 * Copyright 2009 Eat Local Food, LLC
 * Copyright (c) 2007 osCommerce (this file was written after
 * code review of osCommerce).
 *
 * This file is part of gwtCommerce.
 *
 * gwtCommerce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * gwtCommerce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gwtCommerce.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.elf.gwt.store.client.components;

import com.elf.gwt.common.client.GWTCommerceCommonConstants;
import com.elf.gwt.common.client.access.RequestParameter;
import com.elf.gwt.common.client.components.CommonSimpleComponent;
import com.elf.gwt.common.client.model.AccountModel;
import com.elf.gwt.common.client.model.CategoryModel;
import com.elf.gwt.common.client.model.ManufacturerModel;
import com.elf.gwt.common.client.model.ProductModel;
import com.elf.gwt.common.client.model.TellAFriendMetaModel;
import com.elf.gwt.common.client.model.TellAFriendModel;
import com.elf.gwt.common.client.utils.CommonUtils;
import com.elf.gwt.store.client.GWTCommerceConstants;
import com.elf.gwt.store.client.StoreComponentController;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.InlineHTML;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;


/**
 * 
 */
public class TellAFriendEntryComponent extends JSONServerComponent
{
	protected TellAFriendMetaModel tellAFriendMetaModel;
	protected TellAFriendModel tellAFriendModel;

	public static final String TellAFriend = "TellAFriend";

	protected TextBox yourNameBox;
	protected TextBox yourEmailBox;
	protected TextBox friendsNameBox;
	protected TextBox friendsEmailBox;
	protected TextArea yourMessage;
	protected InlineHTML warningLabel;
	protected String action = "";

	/**
	 * Constructor
	 */
	public TellAFriendEntryComponent(StoreComponentController controller, String stylePrefix)
	{
		super(controller, stylePrefix, null, false);
		setupTimer();
		tellAFriendModel = new TellAFriendModel();
		yourMessage = null;
		this.setLoginRequired(true);
	}

	public boolean updateFromHistoryParameters(String[] params)
	{		
		if (!super.updateFromHistoryParameters(params)) return false;

		action = "";

		int productId = StoreComponentController.productComponent.getProductModel().getId();
		int categoryId = StoreComponentController.categoriesComponent.getCategoryModel().getId();
		int manufacturerId = StoreComponentController.manufacturersComponent.getManufacturerModel().getId();
		
		try {
			productId = Integer.parseInt(params[1]);
			categoryId = Integer.parseInt(params[2]);
			manufacturerId = Integer.parseInt(params[3]);
		}
		catch (Exception e) {}

		StoreComponentController.productComponent.getProductModel().update(categoryId, productId, "");

		CategoryModel cmodel = StoreComponentController.categoriesComponent.getCategoryModel(categoryId);
		StoreComponentController.categoriesComponent.getCategoryModel().update(cmodel);

		if (manufacturerId != StoreComponentController.manufacturersComponent.getManufacturerModel().getId())
		{
			ManufacturerModel mmodel = StoreComponentController.manufacturersComponent.getManufacturerModelById(manufacturerId);
			StoreComponentController.manufacturersComponent.getManufacturerModel().update(mmodel);
			StoreComponentController.manufacturersComponent.rebuild();
			storeController.getMultipleResultsComponent().addComponent(StoreComponentController.categoriesComponent);
		}

		storeController.getMultipleResultsComponent().addComponent(StoreComponentController.productComponent);
		storeController.getMultipleResultsComponent().addComponent(this);

		//Don't look for new products
		CommonSimpleComponent alwaysAskComponent = controller.getComponent("NewProductsComponent", false);
		if (alwaysAskComponent != null) storeController.getMultipleResultsComponent().removeComponent(alwaysAskComponent);
		
		return true;
	}

	public void onBuilt()
	{
		Window.scrollTo(0, 0);
		StoreComponentController.productComponent.setVisible(false);
		super.onBuilt();
	}

	/**
	 * add the additional request parameters.
	 */
	public void additionalRequestParameters()
	{
		super.additionalRequestParameters();
		if (action.length() > 0)
		{
			addRequestParameter(new RequestParameter("action", action));
			addRequestParameter(new RequestParameter("your_name", tellAFriendModel.getYourName()));
			addRequestParameter(new RequestParameter("your_email_address", tellAFriendModel.getYourEmailAddress()));
			addRequestParameter(new RequestParameter("friends_name", tellAFriendModel.getFriendsName()));
			addRequestParameter(new RequestParameter("friends_email_address", tellAFriendModel.getFriendsEmailAddress()));
			addRequestParameter(new RequestParameter("your_message", tellAFriendModel.getYourMessage()));
		}
		action = "";
	}

	/**
	 * Build a TellAFriendMetaModel.
	 */
	protected void buildMetaModel(JSONObject jsonObject) throws Exception
	{
		tellAFriendMetaModel = new TellAFriendMetaModel(jsonObject);
	}

	/**
	 * Build a TellAFriendModel.
	 */
	protected void buildModel(JSONObject jsonObject) throws Exception
	{
		tellAFriendModel = new TellAFriendModel(jsonObject);
		tellAFriendModel.update(tellAFriendModel);
	}

	/**
	 * Create the visuals for the component
	 */
	public void buildFromModel() throws Exception
	{
		GWTCommerceConstants constants = storeController.getStoreConstants();
		AccountModel accountModel = StoreComponentController.accountComponent.getAccountModel();
		panel.setText(0, 0, constants.TellAFriendEntryComponentTitle() + " '" + StoreComponentController.productComponent.getProductModel().getName() + "'");
		if (yourMessage == null)
		{
			FlowPanel bodyPanel = new FlowPanel();
			panel.setWidget(1, 0, bodyPanel);
			bodyPanel.add(new InlineHTML("<br/>"));
			bodyPanel.add(new InlineHTML("<br/>"));
			InlineLabel detailsTitle = new InlineLabel(constants.TellAFriendEntryComponentYourDetails());
			detailsTitle.setStyleName(handle + "SubTitle");
			detailsTitle.setWordWrap(false);
			InlineLabel requiredTitle = new InlineLabel(constants.AccountComponentRequired());
			requiredTitle.setStyleName(handle + "RequiredTitle");
			HorizontalPanel detailsTitlePanel = new HorizontalPanel();
			detailsTitlePanel.setStyleName(handle + "DetailsTitlePanel");
			detailsTitlePanel.add(detailsTitle);
			detailsTitlePanel.add(requiredTitle);
			detailsTitlePanel.setCellWidth(requiredTitle, "100%");
			bodyPanel.add(detailsTitlePanel);
			detailsTitlePanel.setCellHorizontalAlignment(requiredTitle, HasHorizontalAlignment.ALIGN_RIGHT);

			Grid yourGrid = new Grid(2,3);
			yourGrid.setWidth("100%");
			yourGrid.setStyleName(handle + "SubPanel");
			yourGrid.getColumnFormatter().setStyleName(0, handle + "SubPanelCol0");
			bodyPanel.add(yourGrid);
			bodyPanel.add(new InlineHTML("<br/>"));

			yourNameBox = new TextBox(); 
			yourNameBox.setText("");
			yourNameBox.setEnabled(true);
			CommonUtils.addGridWidget(getHandle(), 0, yourNameBox, yourGrid, "your_name", constants.TellAFriendEntryComponentYourName(), constants.TellAFriendEntryComponentYourNameText());
			yourEmailBox = new TextBox(); 
			yourEmailBox.setText("");
			yourEmailBox.setEnabled(true);
			CommonUtils.addGridWidget(getHandle(), 1, yourEmailBox, yourGrid, "your_email_address", constants.TellAFriendEntryComponentYourEmailAddress(), constants.TellAFriendEntryComponentYourEmailAddressText());

			CommonUtils.addSubTitle(getHandle(), bodyPanel, constants.TellAFriendEntryComponentYourFriendsDetails());

			Grid friendsGrid = new Grid(2,3);
			friendsGrid.setWidth("100%");
			friendsGrid.setStyleName(handle + "SubPanel");
			friendsGrid.getColumnFormatter().setStyleName(0, handle + "SubPanelCol0");
			bodyPanel.add(friendsGrid);
			bodyPanel.add(new InlineHTML("<br/>"));

			CommonUtils.addSubTitle(getHandle(), bodyPanel, constants.TellAFriendEntryComponentYourMessage());
			friendsNameBox = new TextBox(); 
			CommonUtils.addGridWidget(getHandle(), 0, friendsNameBox, friendsGrid, "friends_name", constants.TellAFriendEntryComponentYourFriendsName(), constants.TellAFriendEntryComponentYourFriendsNameText());
			friendsEmailBox = new TextBox(); 
			CommonUtils.addGridWidget(getHandle(), 1, friendsEmailBox, friendsGrid, "friends_email_address", constants.TellAFriendEntryComponentYourFriendsEmailAddress(), constants.TellAFriendEntryComponentYourFriendsEmailAddressText());

			yourMessage = new TextArea();
			yourMessage.setWidth("100%");
			yourMessage.setCharacterWidth(200);
			yourMessage.setVisibleLines(15);
			bodyPanel.add(yourMessage);
			warningLabel = new InlineHTML("");
			warningLabel.setStyleName("WarningLabel");
			warningLabel.addStyleName(getHandle() + "WarningLabel");
			bodyPanel.add(warningLabel);

			HorizontalPanel buttonPanel = new HorizontalPanel();
			Button editButton = new Button(controller.getCommonConstants().Continue(), 
					new ClickHandler() {
						public void onClick(ClickEvent event) {
							GWTCommerceConstants constants = storeController.getStoreConstants();
							GWTCommerceCommonConstants commonConstants = controller.getCommonConstants();
							StringBuffer warningText = new StringBuffer();
							if (!CommonUtils.validateEmailFormat(yourEmailBox.getText()))
							{
								warningText.append("\n");
								warningText.append(constants.TellAFriendEntryComponentYourEmailAddressInvalidFormat());
							}
							if (!CommonUtils.validateEmailFormat(friendsEmailBox.getText()))
							{
								warningText.append("\n");
								warningText.append(constants.TellAFriendEntryComponentYourFriendsEmailAddressInvalidFormat());
							}

							warningText = CommonUtils.lengthWarning(commonConstants, warningText, yourNameBox, constants.TellAFriendEntryComponentYourName(), 1);
							warningText = CommonUtils.lengthWarning(commonConstants, warningText, friendsNameBox, constants.TellAFriendEntryComponentYourFriendsName(), 1);

							if (warningText.length() > 0)
								Window.alert(warningText.toString());
							else
							{
								tellAFriendModel.setYourName(yourNameBox.getText());
								tellAFriendModel.setYourEmailAddress(yourEmailBox.getText());
								tellAFriendModel.setFriendsName(friendsNameBox.getText());
								tellAFriendModel.setFriendsEmailAddress(friendsEmailBox.getText());
								tellAFriendModel.setYourMessage(yourMessage.getText());
								action = TellAFriend;
								build(true);
							}
						}}
			);
			buttonPanel.add(editButton);

			Button cancelButton = new Button(controller.getCommonConstants().GoBack(), 
					new ClickHandler() {
						public void onClick(ClickEvent event) {
							ProductModel productModel = StoreComponentController.productComponent.getProductModel();
							onSelection("ProductComponent--" + productModel.getId() + "--" + productModel.getCategoryId() 
									+ "--" + StoreComponentController.manufacturersComponent.getManufacturerModel().getId());
						}}
			);
			buttonPanel.setWidth("100%");
			buttonPanel.add(cancelButton);
			buttonPanel.setCellHorizontalAlignment(cancelButton, HasHorizontalAlignment.ALIGN_RIGHT);
			bodyPanel.add(buttonPanel);
		}

		if (accountModel.getId() > 0)
		{
			String name = accountModel.getFirstname() + " " + accountModel.getLastname();
			yourNameBox.setText(name);
			yourNameBox.setEnabled(false);

			String emailAddress = accountModel.getEmailAddress();
			if (emailAddress != null  & emailAddress.length() > 0)
			{
				yourEmailBox.setText(emailAddress);
				yourEmailBox.setEnabled(false);
			}
			else
			{
				yourEmailBox.setEnabled(true);
			}
		}
		else
		{
		yourNameBox.setEnabled(true);
		yourEmailBox.setEnabled(true);
		}

		int errorCode = tellAFriendModel.getErrorCode();
		
		if (accountModel.getId() < 1 && !tellAFriendMetaModel.isAllowGuest())
		{
			errorCode = -80;
		}
		
		if (errorCode < 0)
		{
			if (errorCode == -10)
				warningLabel.setText(constants.TellAFriendEntryComponentProductIdInvalid());
			else if (errorCode == -20)
				warningLabel.setText(constants.TellAFriendEntryComponentNotLoggedInAfterSend());
			else if (errorCode == -30)
				warningLabel.setText(constants.TellAFriendEntryComponentYourEmailAddressInvalidDomain());
			else if (errorCode == -40)
				warningLabel.setText(constants.TellAFriendEntryComponentYourFriendsEmailAddressInvalidDomain());
			else if (errorCode == -50)
				warningLabel.setText(constants.TellAFriendEntryComponentYourNameRequired());
			else if (errorCode == -60)
				warningLabel.setText(constants.TellAFriendEntryComponentYourFriendsNameRequired());
			else
				warningLabel.setText(constants.TellAFriendEntryComponentUnknownError());
		}
		else if (errorCode > 0)
		{
			warningLabel.setHTML("<span class=\"SuccessLabel\">Email sent to your friend.</span>");
			tellAFriendModel.setErrorCode(0);
		}
		else
			warningLabel.setText("");

		onBuilt();
	}

	public TellAFriendModel getTellAFriendModel()
	{
		return tellAFriendModel;
	}
}
